package com.yvon.maple.service.auth.authentication.granter;

import cn.hutool.core.util.StrUtil;
import com.yvon.boot.jwt.model.AuthInfo;
import com.yvon.boot.jwt.utils.TokenUtil;
import com.yvon.boot.redis.service.RedisService;
import com.yvon.maple.service.auth.authentication.mobile.SmsAuthenticationToken;
import com.yvon.maple.service.auth.domain.SecurityUser;
import com.yvon.maple.service.auth.param.LoginParam;
import com.yvon.maple.service.auth.service.SecurityUserService;
import com.yvon.maple.service.auth.enums.CodeTypeEnum;
import com.yvon.maple.service.auth.valicode.validate.code.processor.CodeValidator;
import com.yvon.maple.service.auth.vo.ValidateVo;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author : Yvon
 * @since : 2021-08-23
 */
@Component(SmsTokenGranter.GRANT_TYPE)
public class SmsTokenGranter extends AbstractTokenGranter implements TokenGranter {

    public static final String GRANT_TYPE = "sms";


    public SmsTokenGranter(TokenUtil tokenUtil, AuthenticationManager authenticationManager, SecurityUserService securityUserService, CodeValidator codeValidator, RedisService redisService) {
        super(tokenUtil, authenticationManager, securityUserService,codeValidator, redisService);

    }

    @Override
    public AuthInfo grant(LoginParam loginParam) {
        if (StrUtil.isEmpty(loginParam.getMobile()) || StrUtil.isEmpty(loginParam.getCode())) {
            throw new UsernameNotFoundException("请输入短信验证码");
        }
        validateCode(loginParam);
        // 3. 登录
        SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(loginParam.getMobile(), loginParam.getCode());
        Authentication authentication = authenticationManager.authenticate(smsAuthenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        storageUserInfo(securityUser);
        return this.createToken(securityUser);
    }
}
